﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace NHibernate.MappingGenerator
{
	public enum SqlConnectionTypeEnum
	{
		Windows,
		Sql
	}

	public class ServerConnectionParameters
	{
		private bool _isNew = true;

		public Guid Id { get; set; }
		public string DisplayName { get; set; }
		public string ServerName { get; set; }
		public SqlConnectionTypeEnum ConnectionType { get; set; }
		public string Username { get; set; }
		public string Password { get; set; }
		public bool IsNew
		{
			get
			{
				return _isNew;
			}

			private set
			{
				_isNew = value;
			}
		}

		public static IList<ServerConnectionParameters> GetSavedConnections()
		{
			IList<ServerConnectionParameters> list = new List<ServerConnectionParameters>();

			string xmlFile = Path.Combine(Environment.CurrentDirectory, "GeneratorSettings.xml");

			XDocument document = XDocument.Load(xmlFile);

			IEnumerable<XElement> servers = document.Descendants("ServerConnection");

			foreach (XElement server in servers)
			{
				ServerConnectionParameters parameters = new ServerConnectionParameters();

				SqlConnectionTypeEnum outParam = SqlConnectionTypeEnum.Windows;

				if (string.IsNullOrEmpty(server.Attribute("id").Value))
					parameters.Id = Guid.NewGuid();
				else
					parameters.Id = Guid.Parse(server.Attribute("id").Value);

				parameters.ServerName = server.Attribute("serverName").Value;
				
				parameters.ConnectionType = outParam;
				if (Enum.TryParse<SqlConnectionTypeEnum>(server.Attribute("typeConnection").Value, out outParam))
					parameters.ConnectionType = outParam;
				parameters.Username = server.Attribute("username").Value;
				parameters.Password = server.Attribute("password").Value;
				parameters.DisplayName = server.Attribute("displayName").Value;
				parameters.IsNew = false;

				list.Add(parameters);
			}

			return list;
		}
	}
}
